package com.duowan.cms.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadHelper {

	 private Map<String,String> formFieldMap = new HashMap<String,String>();//用于存放表单数据
	 private List<FileItem> fileItemList = new ArrayList<FileItem>();//用于存放文件数据
     
	 public FileUploadHelper(HttpServletRequest request) throws UnsupportedEncodingException{
			this.upload(request);
	 }
	 
     private void upload(HttpServletRequest request) throws UnsupportedEncodingException{
         List<FileItem>   items = this.getFileItemList(request);
         Iterator<FileItem> fii = items.iterator();
         while(fii.hasNext()){  
	       	 FileItem fis = (FileItem)fii.next();//从集合中获得一个文件流  
	           if (fis.isFormField()) {  
	    			formFieldMap.put(fis.getFieldName(), fis.getString("UTF-8"));
	           } else if(!fis.isFormField() && fis.getName().length()>0){//过滤掉表单中非文件域  
	        	   	fileItemList.add(fis);
	           }  
         }
     }
 	/**
 	 * 从流数据中得到集合数据
 	 * @param request
 	 * @return
 	 */
 	private List<FileItem> getFileItemList(HttpServletRequest request){
 		 DiskFileItemFactory dff = new DiskFileItemFactory();//创建该对象  
           dff.setSizeThreshold(102400000);//指定在内存中缓存数据大小,单位为byte  
           ServletFileUpload fileUpload = new ServletFileUpload(dff);//创建该对象  
           fileUpload.setHeaderEncoding("UTF-8");
           fileUpload.setFileSizeMax(102400000);//指定单个上传文件的最大尺寸  
           fileUpload.setSizeMax(102400000);//指定一次上传多个文件的总尺寸  
           try {
 			return  fileUpload.parseRequest(request);
 			} catch (FileUploadException e) {
 				//TODO:上传过程中的异常处理
 				e.printStackTrace();
 			}
            return null;
 	}

	public List<FileItem> getFileItemList() {
		return fileItemList;
	}
	public void setFileItemList(List<FileItem> fileItemList) {
		this.fileItemList = fileItemList;
	}
	public String  getFieldValue(String fieldName ){
		return formFieldMap.get(fieldName);
	}
	public Map<String,String> getFormFieldMap(){
		return formFieldMap;
	}
}
